package test2;


import cn.hutool.json.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.nio.charset.StandardCharsets;

/**
 * @author liule
 * @date 2023/8/7 14:37
 * @Desc : 发送multipart/form-data类型上传文件的post请求
 */
public class HttpClientTest4_post_multipart {
    public static void main(String[] args) throws Exception {
        //可关闭的httpclient客户端，相当于你打开的一个浏览器
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        String urlstr = "http://localhost:8899/httpclient-demo/test3multi";
        // 创建HttpPost
        HttpPost httpPost = new HttpPost(urlstr);
        // 设置
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setCharset(Consts.UTF_8);// 设置编码
//        builder.setContentType(ContentType.MULTIPART_FORM_DATA); //中文乱码
        builder.setContentType(ContentType.create("multipart/form-data", Consts.UTF_8));
        // 对于普通的表单字段如果含有中文的话，不能通过addTextBody，否则乱码
        // text:指的是输入的值

        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);// 设置浏览器模式
        // 创建一个ContentBody的实现类对象
        FileBody fileBody = new FileBody(new File("D:\\javaWork\\study\\test20220719\\src\\main\\resources\\image\\abc.png"));
        HttpEntity multipartEntity = builder.addPart("fileName", fileBody)
                // 通过file，byte[]，inputstream上传文件
                .addBinaryBody("fileName", new File("D:\\javaWork\\study\\test20220719\\src\\main\\resources\\image\\abc.png"))
                .addTextBody("userName", "小明")
                .addTextBody("password", "123456")
                .build();

        httpPost.setEntity(multipartEntity);

        // 可关闭的响应
        CloseableHttpResponse response = null;
        try {
            response = closeableHttpClient.execute(httpPost);
            // 代表本次请求的成功失败的状态
            StatusLine statusLine = response.getStatusLine();
            if (HttpStatus.SC_OK == statusLine.getStatusCode()) {
                HttpEntity entity = response.getEntity();
                String toStringSesult = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                System.out.println(toStringSesult);
                EntityUtils.consume(entity); // 确保流关闭
            } else {
                System.out.println("响应失败，响应码：" + statusLine.getStatusCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (closeableHttpClient != null) {
                closeableHttpClient.close();
            }
            if (response != null) {
                response.close();
            }
        }

    }
}
